package com.ziqikeji.xianyan.common;

import com.ziqikeji.xianyan.enumeration.DeleteFlagEnum;
import com.ziqikeji.xianyan.enumeration.YesOrNoEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author liuyu
 */
@Component
@Transactional
public abstract class BaseService<T extends BaseEntity, D extends BaseDao<T, String>> {

    @Autowired
    private D dao;

    public BaseService() {
    }

    public T get(String id) {
        return this.dao.findById(id).isPresent() ? this.dao.findById(id).get() : null;
    }

    public Page<T> getPage(int pageNumber, int pageSize) {
        Pageable pageable = PageRequest.of(pageNumber, pageSize, new Sort(Sort.Direction.ASC, "createTime"));
        return this.dao.queryByDeleteFlagEnum(DeleteFlagEnum.NO_DELETE, pageable);
    }

    public List<T> getAll() {
        return (List<T>) this.dao.findAll();
    }

    public List<T> getAllNoDelete() {
        return this.dao.findByDeleteFlagEnum(DeleteFlagEnum.NO_DELETE);
    }

    public T save(T t) {
        t.setCreateTime(new Date());
        t.setDeleteFlagEnum(DeleteFlagEnum.NO_DELETE);
        return this.dao.save(t);
    }

    public T update(T t) {
        t.setUpdateTime(new Date());
        t.setDeleteFlagEnum(DeleteFlagEnum.NO_DELETE);
        return this.dao.save(t);
    }

    public void deleteMark(String id) {
        Optional<T> optional = this.dao.findById(id);
        if (optional.isPresent()) {
            T t = optional.get();
            t.setDeleteFlagEnum(DeleteFlagEnum.DELETE);
            this.dao.save(t);
        }
    }

    public void delete(T t) {
        this.dao.delete(t);
    }
}
